from sqlalchemy.orm import Session
from core.database import SessionLocal
from core.logger import log
from db.mysql.template import Template


class TemplateDao:
    def __init__(self,db: Session = None):
        self.db = db or SessionLocal()

    def create_template(self,template_data: dict,auto_commit=True):
        """
        创建模板
        :param template_data:
        :param auto_commit:
        :return:
        """
        try:
            template = Template(**template_data)
            self.db.add(template)
            if auto_commit:
                self.db.commit()
                self.db.refresh(template)
            else:
                self.db.flush()
            log.info("模板创建成功", template)
            return template
        except Exception as e:
            log.error("模板创建失败", e)
            if auto_commit:
                self.db.rollback()
            else:
                raise
    def update_template(self,template_id: int, template_data: dict, auto_commit=True):
        """
        更新模板
        :param template_id:
        :param template_data:
        :param auto_commit:
        :return:
        """
        try:
            template = self.db.query(Template).filter(Template.id == template_id).first()
            if template:
                for key, value in template_data.items():
                    setattr(template, key, value)
                if auto_commit:
                    self.db.commit()
                    self.db.refresh(template)
                else:
                    self.db.flush()
                log.info("模板更新成功", template)
                return template
            raise Exception("模板不存在")
        except Exception as e:
            log.error(f"更新模板失败: {str(e)}")
            if auto_commit:
                self.db.rollback()
            else:
                raise  # 重新抛出异常让外层处理
    def delete_template(self,template_id: int, auto_commit=True):
        """
        删除模板
        :param template_id:
        :return:
        """
        try:
            template = self.db.query(Template).filter(Template.id == template_id).first()
            if template:
                self.db.delete(template)
                if auto_commit:
                    self.db.commit()
                else:
                    self.db.flush()
                log.info("模板删除成功", template)
                return template
            raise Exception("模板不存在")
        except Exception as e:
            log.error(f"删除模板失败: {str(e)}")
            if auto_commit:
                self.db.rollback()
            else:
                raise
    def get_template_by_id(self, template_id: str):
        """
        获取模板
        :param template_id:
        :return:
        """
        try:
            template = self.db.query(Template).filter(Template.template_id == template_id).first()
            if template:
                log.info("获取模板成功", template)
                return template
            raise Exception("模板不存在")
        except Exception as e:
            log.error(f"获取模板失败: {str(e)}")
    def get_all_templates_by_user(self,user_id: str)-> list:
        """
        获取所有模板
        :return:
        """
        try:
            templates = self.db.query(Template).filter(Template.user_id == user_id).all()
            log.info("获取所有模板成功", templates)
            return templates
        except Exception as e:
            log.error(f"获取所有模板失败: {str(e)}")


